#!/usr/bin/perl

use warnings;

$0=~m/^(.+)\/[^\/]+$/;
require "$1/config.pl";

$|=1;

my $pidfile = '/var/run/sqlim.pid';
if (-e $pidfile) {
    open(PIDFILE, $pidfile) || die "$pidfile exist, but i cant read it";
    my $oldpid=<PIDFILE>;
    close PIDFILE;
    if ($oldpid > 1 && kill(0,$oldpid)) {
        die "already running, pid=$oldpid";
    } else {
        warn "stale pidfile found! pid=$oldpid";
    }
}
open(PID, ">$pidfile") or die "Can't create $pidfile: $^E";
print PID $$;
close(PID);


my $dbh = db_connect();
my ($cur_month,$cur_year,$default_limit_month,$fsize,$r);
my ($pos, $last_month, $last_year) = $dbh->selectrow_array("SELECT pos,last_month, last_year FROM vars");
my $sth = $dbh->prepare("INSERT INTO access_log (date,duration,client_ip,request,result,size,url,user,http_type) VALUES (?,?,?,?,?,?,?,?,?)") ||die "$^E";
my $sth2 = $dbh->prepare("UPDATE vars SET pos=?;") ||die "$^E";
my $sth3 = $dbh->prepare("UPDATE users SET traffic_month=traffic_month+? WHERE user=?;") ||die "$^E";
my $sth4 = $dbh->prepare("INSERT INTO users (traffic_month,user,limit_month) VALUES (?,?,?);") ||die "$^E";

open(LOG,"<$cfg_access_log")|| die "$cfg_access_log: $^E";
$fsize=(stat($cfg_access_log))[7];
$pos=($fsize < $pos ? 0 : $pos);
seek(LOG,$pos,0);
#while (1) {
($cur_month,$cur_year) = (localtime)[4,5];
$cur_month++;$cur_year+=1900;
$default_limit_month = $dbh->selectrow_array("SELECT limit_month FROM users WHERE id=1");    

if ($last_month!=$cur_month or $last_year!=$cur_year) {
    print "reseting month traffic\n";
    $dbh->do("UPDATE users SET traffic_month=0;") || die "db error: $^E";
    $dbh->do("UPDATE vars SET last_month=$cur_month, last_year=$cur_year;")
        || die "db error: $^E";
    # purge old info
    my ($m,$y);
    if ($cfg_store_month > 0) {
      $m=$last_month-$cfg_store_month;$y=$last_year;
      if ($m<1) { $m+=12; $y--; }
      print "purging old records...";
      $r = $dbh->do("DELETE FROM access_log_sum WHERE date<(current_date - interval $cfg_store_month month)") || die "db error: $^E";
      print "$r deleted\n";
    }
}

while(<LOG>){
    if (/^(\d{10}).\d{3}\s+(\d+)\s+(\S+)\s+([A-Z_\-]+)\/([0-9]{3})\s+([0-9]+)\s+(\S+)\s+(\S+)\s+(\S+)\s+\S+\s+(\S+)/) {
        my $datetime=$1;
        my $duration=$2;
        my $client_ip=$3;
        my $request=$4;
        my $result=$5;
        my $size=$6;
        my $method=$7;
        my $url=lc($8);
        my $user=lc($9);
        my $http_type=$10;
        my ($seconds, $minutes, $hours, $day_of_month, $month, $year,
            $wday, $yday, $isdst) = localtime($datetime);
	# remove domain part
	$user=remove_domain($user);
        $month++;$year+=1900;
        $datetime="$year-$month-$day_of_month $hours:$minutes:$seconds";
        next if ($result==407); #Skip deny events from calculating
        next if ($request eq 'TCP_DENIED');
		next if ($size==0);
        $pos=tell(LOG);
        unless ($method eq "CONNECT") {
            if ($url=~m|^\S+://([^/]+)|) {
                $url=$1;
            }
        }
        #############
        $size*=1.5 if ($user eq 'bratchikov');
        $size*=1.5 if ($user eq 'pavel');
        $size*=1.5 if ($user eq 'morozov');
        #############
        next if defined($s{$user}{$url});$s=$s;
        
        $sth->execute($datetime,$duration,$client_ip,$request,$result,$size,
            $url,$user,$http_type) || die "db error: $^E";
        $sth2->execute($pos) || die "db error: $^E";
        if ($year==$cur_year && $month==$cur_month) {
            $r=$sth3->execute($size,$user) || die "db error: $^E";
            if ($r==0) {$sth4->execute($size,$user,$default_limit_month) || die "db error: $^E";}
        }
    }
}
=for
    sleep(5);
    seek(LOG,$pos,0);
    if (tell(LOG)<$pos) {
        close(LOG);
        open(LOG,"<$cfg_access_log")|| die "$cfg_access_log: $^E";
        $pos=0;
    }
}
=cut
close(LOG);
$dbh->disconnect;
unlink $pidfile;

